﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using Interfaces;
using Controller;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary; 

namespace Server
{
    public class ClientHandler
    {

        //lånt fra lærerens eksempler
        private Socket clientSocket;
        private NetworkStream netStream;
        private StreamWriter writer;
        private StreamReader reader;
        private Server server;
        private Session session;
        private Responder responder;
        private FacadeController controller;
        object _senderLaas = new object();
        object _readerLaas = new object();

        //\ikke længere lånt
        public ClientHandler(Socket clientSocket, Server server, FacadeController controller)
        {
            this.server = server;
            this.clientSocket = clientSocket;
            this.controller = controller;
        }

        public void RunClient()
        {
            netStream = new NetworkStream(clientSocket);
            writer = new StreamWriter(netStream);
            reader = new StreamReader(netStream);

            HandleDialog();

            writer.Close();
            reader.Close();
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }

        private void HandleDialog()
        {
            //henter session objekt
            string oldSessionID = clientSocket.RemoteEndPoint.ToString();

            session = server.GetSession(oldSessionID);
            if (session == null)
            {
                session = server.StartSession(oldSessionID);
                session.Responder = new Responder(controller);
            }
            responder = session.Responder;

            Console.WriteLine("session er nu aktiv: " + session.SessionId);

            Communicate();

            session.ConnectedClientHandler = null;


        }

        private bool Communicate()
        {
            string command = recieveFromClient();
            if (command == null)
                return false;


            if (command.StartsWith("vis"))
                //beder responderen om at sende "vis" (en liste over auktioner)
                sendToClient(responder.Vis());
            else if (command.StartsWith("byd"))//byder på en auktion
                sendToClient(responder.Byd(command.Trim().Substring(2), session));
            else if (command.StartsWith("tilmeld")) //tilmelder sig en konkret auktion
                sendToClient(responder.Tilmeld(command.Trim().Substring(2), session));
            else
                sendToClient("Ukendt kommando");
            return true;
        }

        private string recieveFromClient()
        {
            lock (_readerLaas)
            {
                try
                {
                    return reader.ReadLine();
                }
                catch
                {
                    return null;
                }
            }

        }

        private void sendToClient(string stringToSend)
        {//ens metoder da vi nogle gange har brug for at sendre strenge, andre gange auktioner-/lister osv.
            lock (_senderLaas)
            {
                writer.WriteLine(stringToSend);
                writer.Flush();
            }

        }
        private void sendToClient(IAuktion auktionTilSending)
        {
            lock (_senderLaas)
            {
                writer.WriteLine(auktionTilSending);
                writer.Flush();
            }

        }

        private void sendToClient(List<IAuktion> auktionerTilSending )
        {
            lock (_senderLaas)
            {
                //IFormatter formatter = new BinaryFormatter();
                //formatter.Serialize(netStream, auktionerTilSending);
                
                
                writer.WriteLine("hej hej");
                writer.Flush();
            }

        }
    }
}
